package vg.services.user_interface_manager.additional_swing_components;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

/**
 * This class realizes close button for tab.
 * @author tzolotuhin
 */
public class SimpleTabWithCloseButton extends JPanel {
	private final static long serialVersionUID = 1L;
    // Icons
    private final ImageIcon closeActiveImageIcon;
    private final ImageIcon closeImageIcon;
    /**
     * Constructor.
     * @param pane - feedback with tabbed pane.
     * @param closeAction
     */
    public SimpleTabWithCloseButton(final JTabbedPane pane, final ActionListener closeAction) {
        super(new GridBagLayout());
        if (pane == null) {
            throw new NullPointerException("TabbedPane is null");
        }
        this.closeActiveImageIcon = new ImageIcon("./data/resources/textures/closeActive.png");
        this.closeImageIcon = new ImageIcon("./data/resources/textures/close.png"); 
        // create components
        this.setOpaque(false);

        JLabel textLabel = new JLabel() {
        	private final static long serialVersionUID = 1L;
            public String getText() {
                int i = pane.indexOfTabComponent(SimpleTabWithCloseButton.this);
                if (i != -1) {
                    return(pane.getTitleAt(i));
                }
                return(null);
            }
        };
        // pack ui
        GridBagConstraints gbc = null;
		gbc = new GridBagConstraints(0,0, 1,1, 1,1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0,0,0,0), 0,0);
        this.add(textLabel, gbc);
        
        gbc = new GridBagConstraints(1,0, 1,1, 0,0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5,15,5,0), 0,0);
        final JLabel closeButton = new JLabel(this.closeImageIcon);
        this.add(closeButton, gbc);
        
        closeButton.addMouseListener(new MouseAdapter() {
        	public void mouseClicked(MouseEvent e) {
        		ActionEvent ae = new ActionEvent(SimpleTabWithCloseButton.this, e.getID(), null);
        	    closeAction.actionPerformed(ae);        		
        	}
            public void mouseEntered(MouseEvent e) {
            	closeButton.setIcon(SimpleTabWithCloseButton.this.closeActiveImageIcon);
            }

            public void mouseExited(MouseEvent e) {
            	closeButton.setIcon(SimpleTabWithCloseButton.this.closeImageIcon);
            }
		});
    }
}
